#!/bin/bash

VERSION=2.1

if [ "$1" == "version" ]
then
	printf "\n$0\n\nVersion: $VERSION\n\n"
	echo Ty Miller
	echo www.projectshellcode.com
	exit
fi


if [ $# -ne 1 ]
then
	printf "\n\tUsage: $0 filename.asm\n"
	printf "\tEg, $0 shellcode.asm\n\n"
	exit
fi

filename=`echo $1 | sed s/".asm$"//`

asmfilecount=`echo $1 | grep -c ".asm$"`
if [ $asmfilecount -eq 0 ]
then
	printf "\n\tUsage: $0 filename.asm (requires a .asm file as input)\n"
	exit
fi

command=nasm
result=`which $command 2>&1 | grep -v "no $command" | grep .`
if [ "$result" == "" ]
then
	printf "\nERROR: $command not found in PATH. Exiting.\n"
	exit
fi

command=xxd
result=`which $command 2>&1 | grep -v "no $command" | grep .`
if [ "$result" == "" ]
then
	printf "\nERROR: $command not found in PATH. Exiting.\n"
	exit
fi

command=gcc
result=`which $command 2>&1 | grep -v "no $command" | grep .`
if [ "$result" == "" ]
then
	printf "\nWARNING: $command not found in PATH. $filename.shellcodetest.c compile will fail. Not exiting since you may not care.\n"
fi


currentdir=`pwd`
cd $currentdir

rm -f $filename.bin
rm -f $filename.shellcode
rm -f $filename.shellcodetest.c
rm -f $filename.shellcodetest.exe
rm -f $filename.shellcodetest


echo
echo Compiling $filename.asm to $filename.bin
echo [nasm -f bin -o $filename.bin $filename.asm]

nasm -f bin -o $filename.bin $filename.asm

echo
echo Converting $filename.bin to $filename.shellcode
echo [xxd -i $filename.bin ... then parsed]

for i in `xxd -i $filename.bin | grep -v '\;' | grep -v unsigned | sed s/" "/" "/ | sed s/","/""/g | sed s/"0x"/"\\\\x"/g`
do
    echo -n "\\$i" >> $filename.shellcode
    echo -n "\\$i"
done
echo


echo
echo Converting $filename.shellcode to $filename.unicode

i=1
counter=0
for x in `cat $filename.shellcode | sed s/"\\\\\x"/" "/g`
do
        if [ $i -eq 1 ]
        then
                one=$x
                let "i=$i+1"
        else
                two=$x
                echo "%u${two}${one}" >> $filename.unicode.tmp
                i=1
        fi
        let "counter=$counter+1"
done

let "counter=$counter%2"
if [ $counter -eq 1 ]
then
        for x in `cat $filename.shellcode | sed s/"\\\\\x"/" "/g`
        do
                lastcode=$x
        done
        echo "%u90${lastcode}" >> $filename.unicode.tmp
fi

unicode=""
cat $filename.unicode.tmp | while read line
do
        echo -n $line >> $filename.unicode
done

rm -f $filename.unicode.tmp


echo
template=$filename-ms07-004.html
echo Inserting un